import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {setup} from "./setup"
import path from 'path'

const FLOW_JOB_TOKEN: string = 'FLOW_JOB_TOKEN'
const SERVICE_CONNECTION_ID: string = 'SERVICE_CONNECTION_ID'
const NUGET_PRIVATE_REPO_CONFIG_PATH: string = 'nugetPrivateRepoConfigPath'
const REPO_IDS: string = 'repoIds'

async function runStep(): Promise<void> {
    const flowJobToken: string | undefined = process.env[FLOW_JOB_TOKEN]
    if (flowJobToken == undefined) {
        let errMsg = 'missing FLOW_JOB_TOKEN'
        throw new Error(errMsg)
    }

    const serviceConnectionId = process.env[SERVICE_CONNECTION_ID];
    if (serviceConnectionId == undefined) {
        let errMsg = 'missing serviceConnection id'
        throw new Error(errMsg)
    }

    const nugetPrivateRepoConfigPath: string | undefined = process.env[NUGET_PRIVATE_REPO_CONFIG_PATH]
    if (nugetPrivateRepoConfigPath == undefined) {
        let errMsg = 'missing nugetPrivateRepoConfigPath'
        throw new Error(errMsg)
    }

    const repoIdStr: string | undefined = process.env[REPO_IDS]
    if (repoIdStr == undefined) {
        let errMsg = 'missing repoIds'
        throw new Error(errMsg)
    }
    const cleanedRepoIdStr = repoIdStr.replace(/^\[|]$/g, '');
    const repoIds: string[] = cleanedRepoIdStr.split(',').map((repoId: string) => repoId.replace(/"/g, ''))

    const absolutePath = path.resolve(nugetPrivateRepoConfigPath)
    await setup(flowJobToken, serviceConnectionId, absolutePath, repoIds.toString())
}

runStep()
    .then(function () {
        step.success('run step successfully!')
    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
